In: Computer Science
Create a form with two inputs name and roll number.And write a
script to validate the inputs.Any of them should not be
empty.
Name will be string and roll number will be number between 1 -10
only
Dear Student ,
As per the requirement submitted above , kindly find the below solution.
Here a new web page with name "validationScript.html" is created, which contains following code.
validationScript.html :
<!DOCTYPE html>
<html lang="en">
<head>
<!-- title for web pages -->
<title>Validation Script</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form onsubmit="return validateInput()">
Name :
<!-- textbox for name -->
<input type="text" id="txtName"/>
<br><br>
Roll Number :
<!-- textbox for rollnumber -->
<input type="text" id="txtRollNumber"/>
<br><br>
<!-- button to submit form -->
<input type="submit"/>
</form>
<!-- <script> is used for javascript -->
<script>
function validateInput()
{
//taking name entered by user
var name=document.getElementById("txtName").value;
var rollNumber=document.getElementById("txtRollNumber").value;
//regular expresiion for name that allows string only
var nameExp = /^[a-zA-Z ]+$/;
//checking inputs
if(name=="")
{
//if name is empty
alert("Enter Name");
return false;//not allow to submit form
}
else if(rollNumber=="")
{
//if roll number is empty
alert("Enter Roll Number");
return false;//not allow to submit form
}
else if(parseInt(rollNumber)<=1 || parseInt(rollNumber) >=10)
{
//if roll number is not in between 1 to 10 then
alert("Enter Roll Number between 1 to 10");
return false;//not allow to submit form
}
else if(!name.match(nameExp))
{
//if name does not contains letters
alert("Name should contains letters only");
return false;//not allow to submit form
}
else{
//when all validations passed
alert("Validations Passed.Submit form");
return true;
}
}
</script>
</body>
</html>
======================================================
Output : Open web page validationScript.html in the browser and will get the screen as shown below
Screen 1 :validationScript.html
Screen 2:Screen when name is empty
Screen 3:Screen when roll number is empty
Screen 4:Screen when roll number is not between 1 to 10
Screen 5:Screen when name contains numbers
Screen 6:Screen when all validation passed
NOTE : PLEASE FEEL FREE TO PROVIDE FEEDBACK ABOUT THE SOLUTION.