I have this simple html and Jquery code. I want to set the setCustomValidity to appear when user inputs 4 characters in the textfield. So far I'm not getting such result in my code:
<html>
<body>
<input type="text" placeholder="Username" oninvalid="setCustomValidity('Please enter username')" oninput="setCustomValidity('')" id="username" name="username"" required>
</body>
<script>
var username = $("#username").val();
if (username.strlen < 4) {
username.setCustomValidity('Username must contain at least 5 characters');
} else {
username.setCustomValidity('');
}
$(document).ready(function() {
$("#username").keyup(checkUsername);
});
</script>
</html>
I tried this:
<script>
var username = $("#username").val();
if (username.strlen < 4) {
username.setCustomValidity('Username must contain at least 5 characters');
} else {
username.setCustomValidity('');
}
$(document).ready(function() {
$("#username").keyup(checkUsername);
});
</script>
But it doesn't work. Can anyone help?
friend why you are not using html5 pattern like
<input type="text" placeholder="Username" pattern=".{5,}" title="Username must contain at least 5 characters" required id="username" name="username">
Note : Now user cant able to enter less than 5 character in user text field
Demo:-
<!DOCTYPE html>
<html>
<body>
<form action="youractionpage.php">
<input type="text" placeholder="Username" pattern=".{5,}" title="Username must contain at least 5 characters" required id="username" name="username">
<input type="submit" value="ok">
</form>
</body>
</html>
There's no such thing as strlen method in string. You may want to use length.
Sooo it should be....
if (username.length <= 4)
I'm not sure if its <= or = for your message is contradicting with your title. I mean this one. Username must contain at least 5 characters but title is username is less than 4 characters.
Related
JavaScript file is not used in the HTML file despite linking it
I am unable to use the JavaScript file and validate my HTML form. I am wondering if the issue is the linking of the src directory is wrong or could it be that I am missing something in my JavaScript code.
<html>
<head>
<title>Registration Page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="js/validation.js" type="text/javascript">
</script>
</head>
<body>
<form action="validate" method="post" name="register">
Full Name: <input type="text" name="name" required/><br/> Email Address: <input type="email" name="email" required/><br/> Address Line 1: <input type="text" name="address1" required/><br/> Address Line 2: <input type="text" name="address2" /><br/> Postal Code: <input type="number" name="postal" required/><br/> Mobile Number: <input type="number" name="mobile" required/><br/> Password: <input type="password" name="password" required/><br/> Confirm Password: <input type="password" name="cfpassword"
required/><br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
function validateForm() {
//Use a regular expression to check for the pattern of the password
var regexPass = "^[0-9]{6}[a-zA-Z]{1}$";
var regexMobile = "^[0-9]{8}$";
var regexPost = "^[0-9]{6}$";
//Retrieve the VALUE from the "password" field found in the "register" form
var password1 = document.forms["register"]["password"].value;
var password2 = document.forms["register"]["cfpassword"].value;
var postalcode = document.forms["register"]["postal"].value;
if (matchPost === null) {
alert("The postal code given in the correct format. Please ensure
that is contains exactly 6 digits.
");
// Return false to tell the form NOT to proceed to the servlet
return false;
}
if (matchMobile === null) {
alert("The mobile number given in the correct format. Please ensure
that is contains exactly 8 digits.
");
// Return false to tell the form NOT to proceed to the servlet
return false;
}
// If password not entered
if (password1 == '')
alert("Please enter Password");
// If confirm password not entered
else if (password2 == '')
alert("Please enter confirm password");
// If Not same return False.
else if (password1 != password2) {
alert("\nPassword did not match: Please try again...")
return false;
}
// If same return True.
else {
return true
}
}
If your JS folder is in the same directory as your html file this code should work. Write a simple alert('ahoy') function in your JS file and reload your html to verify if your JS file is loaded or not.
I am working on a homework assignment and have been wracking my brain trying to figure out how to do the following:
uName -
requires something to be entered (if not throws error),
requires alphanumeric with at least one letter and one character (if not throws error),
otherwise passes checks and increments the checkev counter
password -
requires something to be entered (if not throws an error), requires the character count to be greater than or equal to 8 characters (if not throws an error), otherwise passes checks and increments the checkev counter
At this point, I have the original errors that are triggered by no entry, however, once I test the second case of not meeting alphanumerics or 8 characters I do not get the expected response.
Below is an example of the JS I have written thus far as well as the HTML:
Any help would be largely appreciated! Thank you in advance!
window.onload = init;
function checkRegistration() {
var checkev = 0;
var uName = document.pageForm.userName.value;
var alphaNum = /^[a-z0-9]+$/i;
var password = document.pageForm.password.value;
if (uName == "") {
document.getElementById('userName').innerHTML = "A username is required.";
checkev=0;
} else if (uName.match != alphaNum)
document.getElementById('userName').innerHTML = "Username must contain at least one letter and one number, no special characters.";
{
document.getElementById('userName').innerHTML = "";
checkev++;
}
if (password == "") {
document.getElementById('password').innerHTML = "A password is required.";
checkev = 0;
} else if (password.lenth >= 8)
document.getElementById('password').innerHTML = "A password of at least 8 characters is required.";
else {
document.getElementById('password').innerHTML = "";
checkev++;
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Invitation Page</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<script src="js/registration.js"></script>
</head>
<form name="pageForm">
<form action="#">
<label for="userName">Username:</label>
<input type="text" name="userName" placeholder="Enter your Username" />
<span class="error" id="userName"></span><br><br>
<label for="Password">Password:
</label>
<input type="password" name="password" placeholder="Enter your Password" />
<span class="error" id="password"></span><br><br>
<input type="button" value="Submit" onclick="checkRegistration()">
</form>
</form>
1 typo and 1 logic issue.
Try password.length < 8
<input type="text" name="userName" id="userName" placeholder="Enter your Username" />
<input type="password" name="password" id="password" placeholder="Enter your Password" />
you miss id attribute when you used getElementById()
and good luck...
Do not hard code your validation simply use V4F
Check out https://v4f.js.org for more details
import {Field, Schema} from "v4f";
export Schema({
username: Field()
.alpha()
.min(1)
.required(),
password: Field()
.min(8)
.required()
});
This question already has answers here:
Strip white spaces on input
(4 answers)
Closed 6 years ago.
I have a signup form that requires an email. when a user uses an android device and enters their email, if they have used the device before android auto suggests their email. If the user selects the auto suggestion it ads a trailing blank space at the end. then when the user goes to signup the system says invalid email because of the blank space. users dont always see the blank space. How can I remove the trailing blank space automatically.
I already have a piece of js that uses the check this function to compare email address entered for repeat email.
<form name="account_reg_form" method="post" action="{$rlBase}{if $config.mod_rewrite}{$pageInfo.Path}.html{else}?page={$pageInfo.Path}{/if}" enctype="multipart/form-data">
<div style="margin-top:10px;">
<input style="text-transform:lowercase;" id="eMail" size="45" class="wauto" type="text" name="profile[mail]" {if $smarty.post.profile.mail}value="{$smarty.post.profile.mail}"{/if} required oninput="check(this)" />
</div>
<div style="margin-top:10px;">
<input size="45" class="wauto" id="eMail_repeat" type="text" name="email_addr_repeat" title="Repeat your email address" placeholder="Repeat your email address" required oninput="check(this)" />
</div>
<input type="submit" value="{$lang.next_step}" />
</form>
<script>
function check() {
var email = document.getElementById('eMail');
var emailRepeat = document.getElementById('eMail_repeat');
if (email.value != emailRepeat.value) {
emailRepeat.setCustomValidity('The two email addresses must match.');
} else {
// input is valid -- reset the error message
emailRepeat.setCustomValidity('');
}
}
</script>
<input style="text-transform:lowercase;" id="eMail" size="45" class="wauto" type="text" name="profile[mail]" {if $smarty.post.profile.mail}value="{$smarty.post.profile.mail}"{/if} required oninput="check(this)" />
var email = document.getElementById("eMail").value.trim();
var repeat = document.getElementById("eMail_repeat").value.trim();
demo can be found here. Enter whitespace after the email inputs to check.
edit: Clearer demo can be found here, with sample addresses provided, and highlighting the differences between using .trim() and not using it.
you can use $.trim() function here:
<form name="account_reg_form" method="post" action="{$rlBase}{if $config.mod_rewrite}{$pageInfo.Path}.html{else}?page={$pageInfo.Path}{/if}" enctype="multipart/form-data">
<div style="margin-top:10px;">
<input style="text-transform:lowercase;" id="eMail" size="45" class="wauto" type="text" name="profile[mail]" {if $smarty.post.profile.mail}value="{$smarty.post.profile.mail}"{/if} required oninput="check(this)" />
</div>
<div style="margin-top:10px;">
<input size="45" class="wauto" id="eMail_repeat" type="text" name="email_addr_repeat" title="Repeat your email address" placeholder="Repeat your email address" required oninput="check(this)" />
</div>
<input type="submit" value="{$lang.next_step}" />
</form>
<script>
function check() {
var email = document.getElementById('eMail').value.trim();
var emailRepeat = document.getElementById('eMail_repeat').value.trim();
if (email.value != emailRepeat.value) {
emailRepeat.setCustomValidity('The two email addresses must match.');
} else {
// input is valid -- reset the error message
emailRepeat.setCustomValidity('');
}
}
</script>
<input style="text-transform:lowercase;" id="eMail" size="45" class="wauto" type="text" name="profile[mail]" {if $smarty.post.profile.mail}value="{$smarty.post.profile.mail}"{/if} required oninput="check(this)" />
You can use Javascript's String.replace with this regex /\s+$/. It would replace the text with empty string.
string.replace(/\s+$/, '')
Example:
var testString = " test string ";
console.log(testString.replace(/\s+$/, ''); // logs: " test string"
DEMO
Note: We could have used the trim() function directly but it removes leading as well as trailing spaces whereas we want only trailing. trimLeft and trimRight are neither standerdized nor implemented in all browsers.
Just use the Jquery snippet below so that, even if you select an email with spaces, it will be trimmed using the input bind event.
It even will not allow spaces.
$(function(){
$('#eMail').bind('change', function(){
$(this).val(function(_, v){
return v.replace(/\s+/g, '');
});
});
$('#eMail_repeat').bind('change', function(){
$(this).val(function(_, v){
return v.replace(/\s+/g, '');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="email" id="eMail"/>
<input type="email" id="eMail_repeat"/>
Pls run the code snippet, paste any email with spaces directly, and it automatically trim's the spaces.
Here is a fiddle
I want to create a input field for phone number. I am creating input field using JavaScript dynamically.
<input type="text" id="phone" name="phone">
How to restrict users to type only 10 digit numbers in order to get a phone number.
try this
<input type="text" name="country_code" title="Error Message" pattern="[1-9]{1}[0-9]{9}">
This will ensure
It is numeric
It will be max of 10 chars
First digit is not zero
Use maxlength
<input type="text" maxlength="10" />
You can use maxlength to limit the length. Normally for numeric input you'd use type="number", however this adds a spinny box thing to scroll through numbers, which is completely useless for phone numbers. You can, however, use the pattern attribute to limit input to numbers (and require 10 numbers too, if you want):
<input type="text" maxlength="10" pattern="\d{10}" title="Please enter exactly 10 digits" />
Well I have successfully created my own working answer.
<input type="text" id="phone" name="phone" onkeypress="phoneno()" maxlength="10">
as well as
<script>
function phoneno(){
$('#phone').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
}
</script>
Add a maxlength attribute to your input.
<input type="text" id="phone" name="phone" maxlength="10">
See this working example on JSFiddle.
HTML
<input type="text" name="fieldName" id="fieldSelectorId">
This field only takes at max 10 digits number and do n't accept zero as the first digit.
JQuery
jQuery(document).ready(function () {
jQuery("#fieldSelectorId").keypress(function (e) {
var length = jQuery(this).val().length;
if(length > 9) {
return false;
} else if(e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
} else if((length == 0) && (e.which == 48)) {
return false;
}
});
});
use a maxlength attribute to your input.
<input type="text" id="phone" name="phone" maxlength="10">
See the fiddle demo here Demo
$(document).on('keypress','#typeyourid',function(e){
if($(e.target).prop('value').length>=10){
if(e.keyCode!=32)
{return false}
}})
Advantage is this works with type="number"
This is what I use:
<input type="tel" name="phoneNumber" id="phoneNumber" title="Please use a 10 digit telephone number with no dashes or dots" pattern="[0-9]{10}" required /> <i>10 digits</i>
It clarifies exactly what is expected in the entry and gives usable error messages.
whereas you could use maxLength on the input, and some javascript validation, it will still be necessary to do server side validation anyway.
HTML
<input type="text" id="youridher" size="10">
Use JQuery,
SIZE = 10
$(document).ready(function() {
$("#youridher").bind('keyup', function() {
if($("#youridher").val().length <= SIZE && PHONE_REGEX) {
return true;
}
else {
return false;
}
});
});
maxlength restrict the number of digits which cannot be more than the desired digits but it accepts less than the desired digits. If mobile No maxlength="10" it will not accept 11 but may accept anything upto 10
Here all of the above outputs are giving a 10 digit number, but along with that the input field is accepting characters also, which is not the full solution. In order to set the 10 digit numbers only, we can use an input tag along with that type as number, and in that we can remove the up-down array by writing some small code in css which is shown below along with the input tag.
<input name="phone" maxlength="10" pattern="[1-9]{1}[0-9]{9}" class="form-control" id="mobile" placeholder="Enter your phone Number" type="number">
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
margin: 0;
}
simply include parsley.js file in your document and in input element of mobile number enter this
data-parsley-type= "number" data-parsley-length="[10,10]" data-parsley-length-message= "Enter a Mobile Number"
you can change the message according to your requirement
you also need to initialize parsley.js file in your document by writing
<script type="text/javascript">
$(document).ready(function() {
$('form').parsley();
});
</script>
---above code in your document.***
The snippet below does the job as expected!
<input type="text" name="AUS" pattern="[0-9]{10}" title="You can enter only 10 digits..." />
//type="text" <!-- always -->
//name="AUS" <!-- for Australia -->
//pattern="[0-9]{10}" <!-- 10 digits from 0 to 9 -->
//title="You can enter only 10 digits..." <!-- Pops a warning when input mismatches -->
How to set a textbox format as 8 digit number(00000019)
string i = TextBox1.Text;
string Key = i.ToString().PadLeft(8, '0');
Response.Write(Key);
<input type="text" name='mobile_number' pattern=[0-9]{1}[0-9]{9}>
Please find below code if you want user to restrict with entering 10 digit in input control
<input class="form-control input-md text-box single-line" id="ContactNumber" max="9999999999" min="1000000000" name="ContactNumber" required="required" type="number" value="9876658688">
Benefits -
It will not allow to type any alphabets in input box because type of input box is 'number'
it will allow max 10 digits because max property is set to maximum possible value in 10 digits
it will not allow user to enter anything less than 10 digits as we want to restrict user in 10 digit phone number. min property in code is having minimum possible value in 10 digits so it will tell user to enter valid 10 digit value not less than that.
<label for="name" class="form-label" style="width:50%;">Mobile No:<input type="text" class="form-control" id="phone" name="mobile" pattern="\d{10}" title="Please enter exactly 10 digits" maxlength="10" required/></label>
This code will validate your contact form for non-numerical data entry. It will show an error message to the user when nonnumerical data is entered and fewer than 10 number is entered.
<form action="http://www.cknuckles.com/cgi/echo.cgi" method="get" name="logOn">
User Name:<br />
<input type="text" name="userName" size="25" /><br />
Password:<br />
<input type="password" name="pw" size="25" /><br />
<input type="submit" value="Log In" onClick="validate()"/>
</form>
Thats my HTML, I have figured out how to only get alpha numerical data into the fields, but how do I get it to only allow a User Name that starts with a capital?
<script language="javascript">
</script>
The simplest way to check this is with a regular expression:
function(str){
return /^[A-Z]/.test(str);
}
returns true when the input string starts with a capital, false otherwise. (This particular regular expression - the bits between the // characters - is saying, 'match the start of the string followed by any single character in the range A-Z'.)
In terms of your HTML above, we'll need the contents of the validate() function to determine where the regex match needs to go.
In your validate function, use a regex match like this:
if (titleString.match(/^[A-Z]/))
<ok>
var letter = str[0];
if (letter !== letter.toUpperCase()){
//not uppercase!
}
This will check to see if the username entered starts with a capital letter, and is followed by 5 - 24 alphanumeric characters.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript">
function validate() {
var the_input = document.getElementById('userName').value;
if (!the_input.match(/^[A-Z]([A-Z]|[a-z]|[0-9]){5,24}$/)) {
alert('Your username must begin with a capital letter, and contain between 6 and 25 alphanumeric characters.');
return false;
} else {
alert('Welcome!');
return true;
}
}
</script>
</head>
<body>
<form action="http://www.cknuckles.com/cgi/echo.cgi" method="get" name="logOn">
User Name:<br />
<input type="text" name="userName" id="userName" size="25" /><br />
Password:<br />
<input type="password" name="pw" size="25" /><br />
<input type="submit" value="Log In" onclick="return validate();"/>
</form>
</body>
</html>
As an aside, it should be noted that this will not work if the user has javascript turned off - you may wish to have some server-side validation instead (or in addition) as a fail-safe.