Mein Problem ist, wenn ich auf Senden klicken, sollte es die box
Klasse nur für leere Felder hinzufügen. Aber mein Code fügt die Klasse box
sowohl für gefüllte als auch für ungefüllte Felder hinzu.Hinzufügen und Entfernen von Attribut in Javascript
function validate() {
var a = document.forms["Form"]["uname"].value;
var b = document.forms["Form"]["number"].value;
var c = document.forms["Form"]["mail"].value;
if (a == null || a == "", b == null || b == "", c == null || c == "") {
['uname', 'mobNo', 'mail'].forEach(function(ids) {
document.getElementById(ids).style.border = "1px solid red";
});
return false;
} else if (!a.match(/^([a-zA-Z]{2,30})$/)) {
document.getElementById('uname').className = 'box';
return false;
} else if (!b.match(/^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/)) {
document.getElementById('mobNo').className = 'box';
return false;
} else if (!c.match(/^([\w-\.][email protected]([\w-]+)+(\.[\w-]{2,4})?)$/)) {
document.getElementById('mail').className = 'box';
return false;
}
}
.box {
border: 2px solid red;
}
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<form method="post" name="Form" onsubmit="return validate()" action="" id="form_id">
<fieldset>
<label>NAME:</label>
<input type="text" name="uname" id="uname" class="fields">
<label>MOBILE NUMBER:</label>
<input type="text" name="number" id="mobNo" class="fields" minlength="10" maxlength="10">
<label>EMAIL:</label>
<input type="email" name="mail" id="mail" class="fields">
<button type="submit" name="submit">SUBMIT</button>
</fieldset>
</form>
</body>
</html>
Ihre erste 'if' Klausel ist falsch:' || '= logisch oder' && '= logisch und ->' if (a == null || a == "", b == null || b == "", c == null || c == "") sollte 'if ((a == null || a ==" ") && (b == null || b ==" ") && (c == null || c ==" "))" – Andreas