I'm finding it very difficult to validate 2 text boxes for matching it with a pattern for acadamic year like 2012-13. I've given differnt ids for both the text boxes n have tried to validate seperately but its not happening. Can any of you please help out. I'm a fresher. i've attached my js code. I want an error message if the pattern is not found for both the text boxes.
<html>
<body>
<script type="text/javascript">
window.onchange=function check_it() {
var ay = document.getElementById("ayear").value;
var fy=document.getElementById("fyear").value;
var pattern = /\d{4}-\d{2,4}$/;
if(pattern.test(ay) && pattern.test(fy)){
return true;
} else {
window.alert ("invalid");
return false;
}
}
</script>
<form >
<p> This Report is prepared for the Current Acadamic Year(<input type="text" size="10" id="ayear" >) and the Current Financial Year (<input type="text" size="10" id="fyear" >) on behalf of the Institution.</p>
</form>
</body>
</html>
Try this:
window.onchange=function check_it() {
var ay = document.getElementById("ayear").value;
var fy=document.getElementById("fyear").value;
var pattern = /^\d{4}-\d{2,4}$/;
if(pattern.test(ay) && pattern.test(fy)){
return true;
} else {
window.alert ("invalid");
return false;
}
}
Also, I'd suggest replacing your regex with this:
/^\d{4}-\d{2,4}$/
Because the other regex will also validate for 122012-2012345
Now, the function above will only return true
if both fields pass the test. Otherwise, it will return false
.
Also, I'd suggest always using brackets ( {}
) with your if/else
's. You had a small issue in your code with those.
This:
if (pattern.test(ay))
return false;
else
window.alert ("invalid");
return true;
Should have been:
if (pattern.test(ay)){
return false;
} else {
window.alert ("invalid");
return true;
}
I hope this solution will work for you onBlur
will be triggered automatically when you move your cursor from the text field. If you want you can add a onClick
function too. Here is your code. Use it in the appropriate place.
<script>
function validate(){
var y = document.getElementById("errorResponse");
var x=document.forms["myForm"]["fval"].value;
var z=document.forms["myForm"]["sval"].value;
//Compare the expression
if (x!=z){
y.innerHTML = "Values not missing";
}else{
y.innerHTML = "Correct";
}
}
</script>
<form name="myForm">
First value: <input type="text" name="fval"/><br>
Second value: <input type="text" name="sval" onBlur = "validate()"/>
<div id = "errorResponse"></div>
<input type="submit" value="Submit">
</form>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.