うまくいきました。フォーム検証エラーメッセージがJavaScriptで上書きされています
フォームのfirstname入力フィールドをJavascriptで検証しようとしています。何らかの理由で、エラーメッセージが順番に表示されません。それらのうちのいくつかは他のものを上書きし、ただ1つのエラーメッセージだけが表示され、残りは表示されません。
私はなぜだろうか?誰か私に光をあげてくれますか?ここで
は私のコードです:
// Predefined validator function to check if input is empty or not
var validator = {};
validator.isEmpty = function(input) {
// Stop execution if input isn't string
if (typeof input !== 'string') return false;
if (input.length !== 0) {
for (var i = 0; i < input.length; i++) {
if (input[i] !== " ") {
return false;
}
return true;
}
}
return true;
};
validator.isEmpty(null); // returns false
// Main part to get inputs and apply validation
window.onload = function() {
var signUp = document.getElementById("signUp");
var fName = document.getElementById("fName");
var suButton = document.getElementById("subMit");
// Submit button on the function
suButton.addEventListener('click', function(event) {
isNameValid(fName);
});
signUp.addEventListener('submit', function(event) {
event.preventDefault();
});
function isNameValid(char) {
var val = char.value;
if (validator.isEmpty(val)) {
if (val.length < 2) {
// Display a message if input length is less than 2
char.setCustomValidity("We expect your input should contain at least 2 characters, darling !");
char.style.borderColor = "red";
}
if(!isNaN(val)) {
char.setCustomValidity("Please, enter only characters");
char.style.borderColor = "red";
}
} else {
char.setCustomValidity("");
char.style.borderColor = "green";
}
}
<form id="signUp">
<input type="text" id="fName" name="firstname" placeholder="First name">
<input type="checkbox" name="result" required autofocus> Agree our conditions
<input type="submit" id='subMit' value="SUBMIT">
</form>
ない複製することができ、あなたが – brk
を複製する手順を教えてくださいすることができます@Tiyorあなたのコードをデバッグしていますか?そうでない場合は、[この回答](https://stackoverflow.com/a/19623573/1575353)またはそれ以降の情報をお試しください –
あなたの状態に論理エラーがあります。 if(validator.isEmpty(val))の条件を設定していますが、同じ条件の中に長さが2以上あるかどうかをチェックしようとしています。つまり、入力ボックスに任意の文字を入れると、上記のif条件には入りませんし、常にそれ以外の部分に移動します。 @Bharat、 – Bharat