I am currently trying to create a very simple validation script with JS. Basically, I want a alert to come up if the text inputted into a form is shorter than 5 characters, or longer than 25.
<!doctype html>
<html>
<head>
<title>Password Validator</title>
</head>
<body>
<script>
function validate()
{
var yourpw = document.forms.passwordform.yourpassword.length;
if (yourpw < 5);
{
alert("password is too short");
return false;
}
if (yourpw > 25)
{
alert("your password is too long")
return false;
}
}
</script>
<h1>Password Validator</h1>
<p>Please create a new password below</p>
<p>Be sure you password follows these guidelines</p>
<ul>
<li>No shorter than 5 characters</li>
<li>No longer than 25 characters</li>
</ul>
<br>
<form name="passwordform" method="post" onsubmit="validate();">
<input type="text" name="yourpassword">
<br>
<input type="submit">
</form>
</body>
</html>
I am not sure what exactly I am missing or why it wont work but the goal of what i want is that when text is inputted into the text box named "yourpassword", a script will run that will show a message if either one of these conditions are met: shorter than 5 characters, or longer than 25, warning the person typing that their password does not follow the guidelines, if the password meets the guidelines, then i just want a simple confirmation message to appear. Anyways i appreciate any help as this is frustrating me and making me want to give up learning JS. Thanks
you need to first prevent the default behavour of form submit .
use
function validate(e)
{
e.preventDefault();
var yourpw = document.forms.passwordform.yourpassword.value.length;
... rest of code
}
Try updating your validate function to as follows:
function validate(e) {
e.preventDefault();
var yourpw = document.getElementsByName('yourpassword')[0].value.length;
if (yourpw < 5) {
alert("password is too short");
return false;
}
if (yourpw > 25) {
alert("your password is too long")
return false;
}
}
You need to grab the input fields value, as mentioned, the input field does not have a length (#Xufox) as well as prevent the default behavior for form submission.
Edit:
Full working example:
<!doctype html>
<html>
<head>
<title>Password Validator</title>
</head>
<body>
<script>
function validate(e) {
e.preventDefault();
var yourpw = document.getElementsByName('yourpassword')[0].value.length;
if (yourpw < 5); {
alert("password is too short");
return false;
}
if (yourpw > 25) {
alert("your password is too long")
return false;
}
}
</script>
<h1>Password Validator</h1>
<p>Please create a new password below</p>
<p>Be sure you password follows these guidelines</p>
<ul>
<li>No shorter than 5 characters</li>
<li>No longer than 25 characters</li>
</ul>
<br>
<form name="passwordform" method="post" onsubmit="validate(event);">
<input type="text" name="yourpassword">
<br>
<input type="submit">
</form>
</body>
</html>
Use this : but give id name yourpassword to input field .. So you can take the value easily
var yourpw = document.getElementById("yourpassword").value;
var len = yourpw.length;
If ( len < 5 )
{
alert ("this is short");
}
elseif(len>25)
{
alert(" too long")
}
else
{
//// your code
}
You can easily validate forms via RegExp.
use this function for validate 5 character limit.
var pw = document.getElementById("yourpassword").value;
function isValidatePW(PW){
var pwRegExp - /\d{5}/
return pwRegExp.test(PW);
}
Related
Okay so I know this is probably a headache for most of you but i'm having trouble figuring this out as javascript is not my strong suit.
I'm trying to basically get this one page to load if username and password is not blank but if it is blank I want it to alert to me (specifically window.alert()) that I have not inputted username and/or password.
I cannot seem to figure it out so here it is.
<button type="submit" id="enterButton" onclick="newPage()"><strong>Enter</strong></button>
there is my button where I put my function on
var username = getElementById("userName");
var password = getElementById("passWord");
function newPage() {
if(username.val().length==0 || password.val().length==0){
alert("please enter valid information");
return location.href = "newPage.html";
}
else{
location.href = "newPage.html";
}
}
and here is my failed attempt to initialize my idea.
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if (password==null || password==""){
alert("password can't be blank");
return false;
} else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
<html>
<body>
<body>
<form name="myform" method="post" action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
Try to check first if you can get the value of your username. If you're using plain javascript, you should use document.getElementById("userName").value.
How can I prevent submision if in my text field are entered just specific characters <>{} and not all of special characters? I'm losing my mind :/
I think you are looking for regex expression. Let me know if it's helpful
$(":input").each(function() {
var input = $(this).val();
var regex = new RegExp("^[a-zA-Z]+$");
if(regex.test(input)) {
alert("true");
} else {
alert("false");
return false;
}
})
I don't have an exact answer as you didn't post any sample code. I can only point you to this article https://javascript.info/bubbling-and-capturing which explain how events bubbling works. A solution will be to use event.stopPropagation() in case the validation doesn't pass.
Here an working ex:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
const regex = new RegExp('^[a-zA-Z]+$');
const input = document.forms['someForm']['somename'].value;
if (regex.test(input)) {
console.log("true");
} else {
console.log("false");
return false;
}
}
</script>
</head>
<body>
<form name="someForm" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="somename">
<input type="submit" value="Submit">
</form>
</body>
</html>
I want the nameVerification() function to throw the alert() message when the user hits submit. For example, if the user enters something like 45 in the name field, I want that alert in nameVerification() function to be called. Right now, when the user does type in a number in the name field, the alert() in the formSubmission() function is being called.
Side note:
formSubmissionfunction works perfectly. In other words, if the user enters a number < 13 in the age field, the functions alert() gets called normally with no problems. If the user enters a number > 13, it works, also, without a problem. Just thought I'd let you guys know that too.
signUp.html
<!DOCTYPE html>
<html>
<head>
<title>Signup Form</title>
<script type="text/javascript" src="signUp.js"></script>
</head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="signUp.css">
<body>
<form class="col-md-4 col-md-offset-4" name="formHandler" id="handle">
<div class="moveUsername">
<label for="usr">Name:</label>
<input type="field" class="form-control" id="nameVerify" placeholder="Username" required="required">
</div>
<div class="ageMovement">
<label for="usr" >Age (Must be 13 years or older to play):</label>
<input type="field" class="form-control" id="ageVerify" name="ageChecker" placeholder="Age" required="required">
</div>
<button type="submit" class="btn btn-default" onclick="formSubmission()" onclick="nameVerification()">Submit</button>
</form>
</body>
</html>
signUp.js
function nameVerification() {
var name = document.getElementById("nameVerify").value;
if(typeof name !== 'string') {
alert("That's not a name!");
}
}
function formSubmission() {
var age = document.getElementById("ageVerify").value;
if(age < 13) {
alert("You're too young, you can't play the game");
}
}
age is also a string in this function:
function formSubmission() {
var age = document.getElementById("ageVerify").value;
if(age < 13) {
alert("You're too young, you can't play the game");
}
}
If you want to do a numeric compare, you need to parse first:
function formSubmission() {
var age = document.getElementById("ageVerify").value;
if (age) {
var ageInteger = parseInt(age, 10);
if (ageInteger < 13) {
alert("You're too young, you can't play the game");
}
}
}
You have two onclick attributes on the button
<button type="submit" class="btn btn-default" onclick="formSubmission()" onclick="nameVerification()">Submit</button>
You can only have one
Your typeof test is failing because the value returned from a text input is always of type string. You can test to see if a provided text value is numeric with the following function:
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
The real answer, however, is that you'll need to improve your input validation tests to determine what you want, rather than test for all the things you don't want. For example, testing for a numeric value as above would not work if someone entered "t#^!" in the field, which is likely not a value you would want in a name field. This is where regular expressions, and the built-in validations from HTML5 fields can help.
You can change your nameVerification function as follows:
function nameVerification() {
var name = document.getElementById("nameVerify").value;
if (name) {
var num = parseInt(name) || -1;
if (num >= 0 && num < 13) {
alert("That's not a name!");
}
}
}
and change your onclick values in the html to be:
onclick="formSubmission();nameVerification()"
it's because the javascript is not loaded yet.
Move:
<script type="text/javascript" src="signUp.js"></script>
To just above the </body> tag.
You should use parseInt:
var age = parseInt(document.getElementById("ageVerify").value);
I'm working on a form that is supposed to validate the input in several textboxes when the user clicks the "submit" button. If any of the required boxes are left blank or have an incorrect type of input or format, the border of those textboxes is supposed to turn red and return to the normal color when the requirements are met.
For example, a phone number is either supposed to be 7 or 10 digits long, if the user enters a six digit number like (123456), the border around this field should turn red, when the user enters one more number, like (1234567), the border should go back to it's regular color immediately, without the user having to click the "submit" button again.
How my code is written, the border does turn red when the user enters too few numbers, however, the submit button must be clicked for the border to go back to its original color. Is there a way to change the color back without the button being clicked a second time?
Here is my code:
<html>
<head>
<title>Project 4</title>
<style type="text/css">
.error {
border:2px solid red;
}
</style>
</head>
<body>
<form name="myForm" onsubmit="return validateForm()">
Phone Number:<input type="text" id="phone">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
function validateForm() {
return checkPhone();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
//document.getElementById("phone").className = document.getElementById("phone").className + " error";
//document.getElementById("phone").className = document.getElementById("phone").className.replace(" error", "");
document.getElementById("phone").style.borderColor="red";
return false;
}
}
</script>
</body>
</html>
Once a user submits the form with invalid data, you can attach onkeyup event listener into a input field, and everythime a user types something into the field, the form will be validated
document.getElementById("phone").onkeyup = validateForm;
I wrote once a user submits the form on purpose, since you do not want to fool your visitor by knowing that he typed only one character and he is getting validation error. (he is about to type 5 more characters)
EDIT:
<html>
<head>
<title>Project 4</title>
<style type="text/css">
.error {
border:2px solid red;
}
</style>
</head>
<body>
<form name="myForm" onsubmit="return validateForm()">
Phone Number:<input type="text" id="phone">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
//at first, we define a variable stating that an event listener has been attached onto the field
var validatePhoneOnKeyUpAttached = false;
function validateForm() {
//then, we attach the event listened to the field after the submit, if it has not been done so far
if(!validatePhoneOnKeyUpAttached) {
document.getElementById("phone").onkeyup = checkPhone;
validatePhoneOnKeyUpAttached = true;
}
return checkPhone();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").style.borderColor="transparent";//and you want to remove invalid style
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
//document.getElementById("phone").className = document.getElementById("phone").className + " error";
//document.getElementById("phone").className = document.getElementById("phone").className.replace(" error", "");
document.getElementById("phone").style.borderColor="red";
return false;
}
}
</script>
</body>
You can simply add onkeyup handler for input field:
<input type="text" id="phone" onkeyup="checkPhone()" />
and also make checkPhone function remove error class if input is valid:
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if (phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").className = '';
return true;
}
else if (phoneNum.length < 7 || phoneNum.length > 10) {
document.getElementById("phone").className = 'error';
return false;
}
}
Demo: http://jsfiddle.net/bcxLz4wh/
Use the blur event of your input like this:
<input type="text" id="phone" onblur="validateForm();">
The blur event runs when you control loses the focus. If you need something more immediate you will need to use the keyup event.
I have text box.
Users can enter Student Id into that.
Student id is in this format DIP0001.
First three letters should be DIP and the remaining 4 digits should be numeric and can only upto 4 characters.
So how can I check whether entered data is in this format using javascript.
Please help.....
You could build a regular expression pattern and test it against that value to see if it matches that exact pattern.
HTML FILE:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
</head>
<body>
<label for="studentId">Student ID</label>
<input id="studentId" type="text">
<button id="btn" type="button">Validate</button>
// Embedded script so that you don't have to load an external file
<script>
var input = document.getElementById('studentId');
var btn = document.getElementById('btn');
var pattern = /DIP+\d{1,3}/g;
btn.addEventListener('click', function(){
if(pattern.test(input.value)) {
alert('It enter code here`atches!');
}else {
alert('It does not match!');
}
});
</script>
</body>
</html>
JS FILE:
// This pattern looks something like this: DIP0000
var pattern = /DIP+\d{1,3}/g;
// studentId is the ID of the input field that contains the Student ID
var studentIdInput = document.getElementById('studentId');
// Check the pattern against the provided Student ID
if(pattern.test(studentIdInput.value)) {
alert('It matches the pattern!');
}
EDIT 1: I have built the functionality in the following JSFiddle: http://jsfiddle.net/vldzamfirescu/QBNrW/
Hope it helps!
EDIT2: I have updated the JSFiddle to match any other combinations up to 4 digits; check it out: http://jsfiddle.net/vldzamfirescu/QBNrW/1/ Let me know if it solved your problem!
try this code
<html>
<head>
<script>
function validate(val) {
if (val.value != "") {
var filter = /^[DIP]|[dip]+[\d]{1,4}$/
if (filter.test(val.value)) { return (true); }
else { alert("Please enter currect Student Id"); }
val.focus();
return false;
}
}
</script>
</head>
<body>
<input id="Text1" type="text" onblur="return validate(this);" />
</body>
</html>
Use Regular Expresions.
If found a valid Student ID, the pattern will return true:
function validateStudentId(id) {
var re = /DIP[0-9]{4}/;
return re.test(id);
}
// Edited for use with a click event:
document.getElementById('button').addEventListener('click', function(){
if( validateStudentId(document.getElementById('textBox').value) ){
alert('correct');
}else{
alert('invalid ID');
}
});