How to validate length and match required character? - javascript

I want to hide the submit button if value does not match the required type, I m able to hide it on the length, but my match does not work.
JavaScript Code:
function submitChangej(){
var inputlastName = document.getElementById("lastname");
var inputfirstName = document.getElementById("firstname");
var inputmobileNumber = document.getElementById("mobilenumber");
var inputidNumber = document.getElementById("idnumber");
var firstname = /^[a-zA-Z-\s]{2,128}$/;
var lastname = /^[a-zA-Z-\s]{2,128}$/;
var mobilenumber = /^[0-9]{10,20}$/;
var idnumber = /^([0-9]){2}([0-1][0-9])([0-3][0-9])([0-9]){4}([0-1])([0-9]){2}?$/;
var inputSubmit = document.getElementById("apply");
var Container = document.getElementById('Agreement');
if((inputfirstName.value.length < 2 || inputfirstName.value.length > 128 ) || ( inputlastName.value.length < 2 || inputlastName > 128 ) || (inputmobileNumber.value.length < 10 || inputmobileNumber > 20) || (inputidNumber.value.length < 13)){
Container.style.display = 'none';
}
else{
Container.style.display = 'block';
}
var Container = document.getElementById('Agreement');
if((firstname.match(firstname) != null) || (lastname.match(lastname) != null) || (mobilenumber.match(mobilenumber) != null) || (idnumber.match(idnumber) != null)){
Container.style.display = 'none';
}
else{
Container.style.display = 'block';
}
}
HTML Code:
<form >
<label for="firstname"><span class="starRequired"><b>*</b> </span>First name:</label><br>
<input type="text" name="firstname" id="firstname" required autofocus="autofocus" pattern="[a-zA-Z-\s]{3,128}" onkeyup="submitChangej();" onkeypress="checkFirstname(this.value);" value="">
<br/><label for="lastname"><span class="starRequired"><b>*</b> </span>Last name:</label><br>
<input type="text" name="lastname" required id="lastname" pattern="[a-zA-Z-\s]{3,128}" onkeyup="submitChangej();" onkeypress="checkLastname(this.value);"
onblur="checkLastname(this.value);" value="">
<br/><label for="mobilenumber"><span class="starRequired"><b>*</b> </span>Mobile Number:</label><br/>
<input type="text" name="mobilenumber" required id="mobilenumber" onkeyup="submitChangej();" onkeypress="checkMobilenumber(this.value);"
onblur="checkMobilenumber(this.value);" value="">
<br/><label for="idnumber">ID Number:</label><br/>
<input type="text" name="idnumber" id="idnumber" maxlength="13" onkeyup="submitChangej();" onkeypress="checkIdnumber(this.value);"
onblur="checkIdnumber(this.value);" value="">
<div id="Agreement" style="display:none">
<input type="submit" id="apply" name="apply" value="Apply"
onclick="if(!this.form.terms.checked){alert('Please indicate that you accept the Agreement');return false}"/>
<input type="checkbox" id="terms" name="terms" >
<label id="accept" >I accept the Agreement</label>
<textarea name="textfield" id="textfield" rows="10" cols="105" readonly="readonly" >
1. Acceptance
1.1 I have read and accepted the above terms and conditions.
</textarea>
</span>
</div>
</form>
I than call my method submitChangej()on the fields that i validate.
The button should be hidden when match and length are invalid, if everything is correct than the button should appear. The length work good, but the match of required characters does not match

Change the final lines of your code to:
if(!firstname.test(inputfirstName.value) || !lastname.test(inputlastName.value) || !mobilenumber.test(inputmobileNumber.value) || !idnumber.test(inputidNumber.value)){
Container.style.display = 'none';
}
else {
Container.style.display = 'block';
}
As it was already mentioned you're trying to find a match on a pattern itseld, which has no sense. Then, the match method is used to get a matching string, but you only want to test the string against some pattern, so use the test method instead.

I would suggest simplifying this and letting the browser do more of the leg work for you by putting this in a form on change listener:
inputSubmit.style.display = (document.querySelectorAll('*:invalid').length)? = 'none' : 'block';

Related

email validation accept two dot just in the form

my problem is I want The email should have no spaces in it and the domain name should be either two words separated by a ‘.’ or three words separated by two dots e.g. username#abc.efg.xy.
and not acceptable to more than three dot
<form name="myForm" onsubmit="return validateForm()" method="post" >
Name: <input type="text" name="fname" placeholder="Name">
<br>
Email: <input type="text" name="femail" placeholder="saleh#gmail.com">
<br>
Message: <input class="filed" type="text" size="60" style="height:200px">
<br>
Age : <input type="text" name="fage" placeholder="between 10 and 120">
<br>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["femail"].value;
var z = document.forms["myForm"]["fage"].value;
if (x == "" || x == null || y == "" || z == null) {
alert("You must be filled out");
return false;
}
if (isNaN(z) || z < 10 || z > 120) {
alert("the age should be between 10 and 120 ");
return false;
}
if (!y.includes('#') ) { // i do not how to complete the if condition
alert("The emali not include # or more one . ");
return false;
}
}
</script>
your're in for a ride
You can use a regular expression to test if the input is an email, NOTE the following answer tests true to 99.9% of the email addresses, but could still fail
const emailReg = new RegExp(/^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.){1,2}[a-zA-Z]{2,}))$/)
if (emailReg.test(y)){
//do something if the email is indeed an email
}
I added some examples in a regex validator https://regex101.com/r/vJ7A3N/1/
source: https://emailregex.com/
you could also use <input type="email" id="email" name="email">

How can I verify form passwords match using JavaScript?

I have a basic html form with password and verify password fields. I want to only allow users to continue if passwords match. If passwords do not match, I want there to be a notification to the user.
I think that what I currently have is close, but the JS still doesn't appear to do anything.
HTML
<form class="ajax-form" id="pwreset" method="post" onsubmit="return verifyPassword()" action="/set-password">
<div id="userinput">
<label for="username">Username</label>
<input type="text" id="username" name="username"/><br/>
<label for="new_password">Password</label>
<input type="Password" id="new_password" name="new_password"/><br/>
<label for="verifyPassword">Verify Password</label>
<input type="password" id="verifyPassword" name="verifyPassword"/><br/>
<input type="hidden" id="uuid" name="uuid" value="{{uuid}}"/>
<p><input class="button" type="submit" value="SUBMIT"></p>
</div>
</form>
JS
function verifyPassword() {
let pass1 = document.getElementById("new_password").value;
let pass2 = document.getElementById("verifyPassword").value;
let match = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("new_password").style.borderColor = "#ff0000";
document.getElementById("verifyPassword").style.borderColor = "#ff0000";
match = false;
}
else {
alert("Passwords match.");
}
return match;
}
There are some issues that can come from putting the javascript call in the HTML.
In your case, the function was probably defined after the HTML, so the element didn't have access to it.
You can use this instead:
function verifyPassword() {
let pass1 = document.getElementById("new_password").value;
let pass2 = document.getElementById("verifyPassword").value;
let match = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("new_password").style.borderColor = "#ff0000";
document.getElementById("verifyPassword").style.borderColor = "#ff0000";
match = false;
}
else {
alert("Passwords match.");
}
return match;
}
document.getElementById('pwreset').onsubmit = verifyPassword;
<form class="ajax-form" id="pwreset" method="post" action="/set-password">
<div id="userinput">
<label for="username">Username</label>
<input type="text" id="username" name="username" /><br/>
<label for="new_password">Password</label>
<input type="Password" id="new_password" name="new_password" /><br/>
<label for="verifyPassword">Verify Password</label>
<input type="password" id="verifyPassword" name="verifyPassword" /><br/>
<input type="hidden" id="uuid" name="uuid" value="{{uuid}}" />
<p><input class="button" type="submit" value="SUBMIT"></p>
</div>
</form>
Here is an example. I created a passwordGroup constructor to centralize the information. This way it's easier to write tests also.
var form = document.forms[0];
var pass1 = form.querySelector('[data-password]');
var pass2 = form.querySelector('[data-password-confirmation]');
var submitButton = form.querySelector('button[type="submit"]');
// PasswordGroup constructor
var PasswordGroup = function () {
this.password = '';
this.passwordConfirmation = '';
};
// method to update the passwords values
PasswordGroup.prototype.setValues = function(data) {
this.password = data.password;
this.passwordConfirmation = data.passwordConfirmation;
};
// method to check the password's equality
PasswordGroup.prototype.match = function() {
return !!(this.password
&& this.passwordConfirmation
&& this.password === this.passwordConfirmation);
};
/*
* Enable/disable the submit button if passwords do not match
*/
function validateSubmit() {
if(passwordGroup.match()) {
submitButton.removeAttribute('disabled');
} else {
submitButton.setAttribute('disabled', 'disabled');
}
}
// passwordGroup instance
var passwordGroup = new PasswordGroup();
// objecto to store the current values
var passwordsValues = {
password: '',
passwordConfirmation: '',
};
// event triggered after enter a new value in the password's field
var onPasswordChange = function(e) {
var target = e.target;
var targetValue = target.value;
if(target.dataset.hasOwnProperty('password')) {
passwordsValues.password = targetValue;
} else if (target.dataset.hasOwnProperty('passwordConfirmation')) {
passwordsValues.passwordConfirmation = targetValue;
}
passwordGroup.setValues(passwordsValues);
validateSubmit();
};
// event attribution
pass1.onkeyup = onPasswordChange;
pass2.onkeyup = onPasswordChange;
input {
display: block;
}
<form action="" name='account'>
<input type="text" placeholder="name" />
<input type="password" data-password placeholder="password"/>
<input type="password" data-password-confirmation placeholder="repeat password"/>
<button type="submit" disabled="disabled">Enviar</button>
</form>
<p data-message></p>

Script not targeting certain elements by ID, works fine on others

If one of the identified DOM elements is empty, change the background color to red, if not, change to transparent. Why does this not work on the phone or position fields?
I have another script targeting elements like document.forms["pledge"]["position"] which also works on all other fields but phone and position. What am I missing?
function checkFilled() {
var fname = document.getElementById("fname"),
lname = document.getElementById("lname"),
email = document.getElementById("email"),
country = document.getElementById("country"),
zip = document.getElementById("zip"),
position = document.getElementById("position"),
phone = document.getElementById("phone");
;
if (fname.value != "") {
fname.style.backgroundColor = "transparent";
} else {
fname.style.backgroundColor = "red";
}
if (lname.value != "") {
lname.style.backgroundColor = "transparent";
} else {
lname.style.backgroundColor = "red";
}
if (email.value != "") {
email.style.backgroundColor = "transparent";
} else {
email.style.backgroundColor = "red";
}
if (country.value != "") {
country.style.backgroundColor = "transparent";
} else {
country.style.backgroundColor = "red";
}
if (zip != undefined && zip.value != "") {
zip.style.backgroundColor = "transparent";
} else {
zip.style.backgroundColor = "red";
}
if (position.value != "") {
position.style.backgroundColor = "transparent";
} else {
position.style.backgroundColor = "red";
}
if (phone.value != "") {
phone.style.backgroundColor = "transparent";
} else {
phone.style.backgroundColor = "red";
}
}
HTML
<form name="pledge" id="form">
<input class="input" type="text" id="fname" name="first_name" placeholder="First Name" onchange="checkFilled()">
<input class="input" type="text" id="lname" name="last_name" placeholder="Last Name" onchange="checkFilled()">
<input class="input" type="text" id="position" name="user_position" placeholder="Position in Government" onchange="checkFilled()">
<input class="input" type="text" id="country" name="user_country" placeholder="Country" onchange="checkFilled()">
<input class="input" type="email" id="email" name="user_email" placeholder="Official Government Email" onchange="checkFilled()">
<input class="input" type="number" id="phone" name="user_phone" placeholder="Office Phone Number" onchange="checkFilled()">
<input class="input full-width" type="submit" value="Take The Pledge!">
</form>
https://codepen.io/froggomad/pen/maRJxr
The script was failing because it was trying to handle the zip element which doesn't exist on this form. I mistakenly tried to handle that condition by checking to see if it existed and contained a value and then changing its background color if both conditions weren't true (OOPS)
Working Code
if (zip != undefined) {
if (zip.value != "") {
zip.style.backgroundColor = "transparent";
} else {
zip.style.backgroundColor = "red";
}
}
Your form does not have an element with the zip id and is therefore throwing errors trying to modify the zip style property in the else statement of your zip check since it is null. Since that error causes the function to fail, the position and phone based if statements don't execute.
If you remove the if/else block checking the zip variable, both of those fields work again.

Make Javascript write on page after submit button pressed

Here is a bit of code I have sourced from w3schools which shows that whenever a name is over 10 characters, the page should add a bit of text, in this case, it should add on "hi", but instead, it removes everything from the page and goes onto a new page and only displays "hi". How can I resolve this?
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php" onsubmit="return myFunction()">
Name (max 10 characters): <input type="text" id="fname" size="20" name="fname"><br>
Age (from 1 to 100): <input type="text" id="age" size="20" name="age"><br>
E-mail: <input type="text" id="email" size="20" name="mail"><br><br>
<input type="submit" value="Submit">
</form>
<script>
function myFunction() {
var at = document.getElementById("email").value.indexOf("#");
var age = document.getElementById("age").value;
var fname = document.getElementById("fname").value;
submitOK = "true";
if (fname.length > 10) {
document.write("hi");
}
if (isNaN(age) || age < 1 || age > 100) {
alert("The age must be a number between 1 and 100");
submitOK = "false";
}
if (at == -1) {
alert("Not a valid e-mail!");
submitOK = "false";
}
if (submitOK == "false") {
return false;
}
}
</script>
</body>
</html>
Simply put, don't use document.write(). If you read the nice orange text at the top of the documentation, you'll see why:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
document.write() should only be used while a page is loading, to ouput while it's creating the webpage, and should not be used afterwards. Consider creating a div, and writing to there instead:
function myFunction() {
var at = document.getElementById("email").value.indexOf("#");
var age = document.getElementById("age").value;
var fname = document.getElementById("fname").value;
submitOK = "true";
if (fname.length > 10) {
document.getElementById('result').innerHTML = 'Fname is > 10!';
}
if (isNaN(age) || age < 1 || age > 100) {
alert("The age must be a number between 1 and 100");
submitOK = "false";
}
if (at == -1) {
alert("Not a valid e-mail!");
submitOK = "false";
}
if (submitOK == "false") {
return false;
} else {
alert('Submitted Successfully!');
return false; // Returning false here just for SO Code Snippet
}
}
<form action="/action_page.php" onsubmit="return myFunction()">
Name (max 10 characters): <input type="text" id="fname" size="20" name="fname"><br>
Age (from 1 to 100): <input type="text" id="age" size="20" name="age"><br>
E-mail: <input type="text" id="email" size="20" name="mail"><br><br>
<input type="submit" value="Submit">
<div id="result"></div>
</form>
Additionally, I notice you're setting submitOK = "true". Javascript does have booleans (See this also). Why not use that instead?
submitOK = true;
if (fname.length < 10) {
alert('Your name should be more than 10 characters');
submitOK = false;
}
if (submitOK) { // Same as "if (submitOK == true)"
//Good to go
}

JavaScript if statment don't work

I need help with javascript. here is my problem:
<script type="text/javascript">
function validateForm() {
var ime = document.getElementById('ime');
var prezime = document.getElementById('prezime');
var telefon = document.getElementById('telefon');
var datum = document.getElementById('datum');
var patt1 = /^\+[0-9]+$/;
if (telefon.match(patt1) == null) {
alert("Niste dobro uneli broj");
}
if (ime.value.length == 0 && prezime.value.length == 0 && telefon.value.length == 0 && datum.value.length == 0) {
alert("Niste dobro uneli podatke!");
return false;
}
}
</script>
<form action="popup.php" method="post" onsubmit="return validateForm()">Vase ime:
<input type="text" name="ime" id="ime"> <br/>
Vase prezime:
<input type="text" name="prezime" id="prezime"> <br/>
Broj telefona:
<input type="text" name="telefon" id="telefon"> <br/>
Datum rodjenja:
<input type="text" name="datum" id="datum"> <br/>
<input type="submit" name="save" value="sacuvaj">
</form>
I don't understand why telefon.match(patt1)==null) doesn't work. Please help!
Reason is because you can't apply regex to HTML Element, you can apply it to its value:
var telefon = document.getElementById('telefon').value;
Then you can execute your regex on var telefon
telefon is a DOM element, not a string
telefon.value can be matched
The object stored in telefon will be a DOM element (e.g. HTMLDivElement), which has no method "match". You'll want to extract the pertinent text from that element before matching. How you do that will depend on the exact DOM type:
if (telefon.value.match(patt1) == null) // For form elements...
if (telefon.innerHTML.match(patt1) == null) // For "plain" DOM elements...

Categories

Resources