I have below code that is working fine, but I want to validate textbox TBMonday to force users to enter in the specified pattern. How can I do this with Javascript (Please I don't want to use input type='time')
<input type="text" id="TBMonday" size="7" placeholder="hh:mm-hh:mm" pattern="(2[0-4]|1[0-9]|[1-
9])\:(5[0-9]|4[0-9]|3[0-9]|2[0-9]|1[0-9]|[0-9])-(2[0-4]|1[0-9]|[1-9])\:(5[0-9]|4[0-9]|3[0-
9]|2[0-9]|1[0-9]|[0-9])" onKeyUp="TBMondayEl();">
<input type="text" id="TBMonday2" size="7">
<script>
function TBMondayEl()
{
document.getElementById('TBMonday2').value = document.getElementById('TBMonday').value;
}
</script>
Here is how I finally write my code and it work for me.
<input type="text" id="TBMonday" size="7" placeholder="hh:mm-hh:mm" required
onblur="validateMon();" onKeyUp="TBMondayEl();">
<input type="text" id="TBMonday2" size="7">
<script>
function validateMon(){
var phoneNumber = document.getElementById('TBMonday').value;
var phoneRGEX = /^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]-(0[0-9]|1[0-9]|2[0-3]):[0-5]
[0-9]$/;
var phoneResult = phoneRGEX.test(phoneNumber);
if(phoneResult == false)
{
document.getElementById('TBMonday').value = '';
document.getElementById('TBMonday2').value = '';
alert('Please enter TimeBelt in "HH:MM-HH:MM" format');
return false;
}
return true;
}
<script>
function TBMondayEl()
{
document.getElementById('TBMonday2').value
document.getElementById('TBMonday').value;
}
</script>
Related
I am trying to make a javascript function that will not submit to the next form unless the information is input correctly i.e only numbers. Is there a way to make the HTML unclickable while the information is incorrect?
function checkInput() {
var error = false;
var phonenumber = /^\d{10}$/;
if (!document.getElementById('username').value.match(phonenumberExpression)) {
alert("Phonenumber is invalid");
error = true;
}
if (error == true) {
error = false;
}
}
<p>Phone Number:</p>
<input class='in-sel-style' id='username' type='text' class="form-control input-md" name='username' required=""><br>
<input class='in-sel-style' id="submit" type='submit' name='submit' onclick='return checkInput()'>
You can add event variable into onclick like this :
<input class='in-sel-style' id="submit" type='submit' name = 'submit' onclick = 'checkInput(event)'>
Then in your javascript function try this :
<script>
function checkInput(event){
var error = false;
var phonenumber = /^\d{10}$/;
if (!document.getElementById('username').value.match(phonenumberExpression)){
alert("Phonenumber is invalid");
error =true;
}
if(error==true){
event.preventDefault();
error=false;
}
</script>
Actually you can use HTML5 Form Validation. So just do this:
<input class='in-sel-style' id='username' type='text' class="form-control input-md" name = 'username' required="" pattern="^\d{10}$">
This will work the same way required does.
If you need a more complex thing that you can do with a regular expression you can do something like this:
document.getElementById('username').addEventListener("input", function (event) {
const value = event.target.value;
const phonenumber = /^\d{10}$/;
if (!value.match(phonenumberExpression)) {
email.setCustomValidity("Phonenumber is invalid");
} else {
email.setCustomValidity("");
}
});
a short notice, I would recommend to always use <button type="submit"> instead of <input type="submit">.
I've tried a lot of things but I can't seem to make it work
Problem is whatever I type is considered false, even when I try valid email adress (such as ok#gmail.com)
Here's my code
function validateEmail(email) {
var re = /[^\s#]+#[^\s#]+\.[^\s#]+/;
return re.test(email);
}
var email = $('input[name = pEmail]').val();
$('#nPopupSubmit').click(function () {
if (!validateEmail(email)) {
$('label[id = pEmailError]').show();
$('input[name = pEmail]').focus();
return false;
} else {
whatever
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<form id="popup1" method="post">
<fieldset>
<input id="pEmail" type="text" placeholder="E-mail" value="E-mail" onclick="this.value=''" class="popup_input" name="pEmail" type="text" />
<label id="pEmailError" style="color:#FF0000; display:none;">Error</label>
<button type="submit" id="nPopupSubmit" name="nPopupSubmit">Go !</button>
</fieldset>
</form>
Do any of you have a clue on what's going on ?
Thank you !
Your function doesn't contain error, perhaps your jQuery? Your email variable should be defined after the click, otherwise, email's value would always = "Email" (the default value)
$('#nPopupSubmit').click(function () {
var email = $('#pEmail').val(); //<-- This is where you should put this
if (!validateEmail(email)) {
$('#pEmailError').show();
$('#pEmail').focus();
return false;
} else {
//whatever
}
});
Also, you can simplify your code by using the ids you have already given your elements :)
function validateEmail(email) {
var re = /[^\s#]+#[^\s#]+\.[^\s#]+/;
return re.test(email);
}
$('#nPopupSubmit').click(function () {
var email = $('#pEmail').val();
if (validateEmail(email) !== true) {
$('#pEmailError').show();
$('#pEmail').focus();
return false;
} else {
//whatever
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="popup1" method="post">
<fieldset>
<input id="pEmail" type="text" placeholder="E-mail" value="E-mail" onclick="this.value=''" class="popup_input" name="pEmail" type="text" />
<label id="pEmailError" style="color:#FF0000; display:none;">Error</label>
<button type="submit" id="nPopupSubmit" name="nPopupSubmit">Go !</button>
</fieldset>
</form>
Your current regex won't validate how you want.
You can try this:
function validateEmail(email) {
var re = new RegExp("^[^\\s#]+#[^\\s#]+?\\.[^\\s#]+$", "m");
console.log(email.match(re));
if(email.match(re))
{
return true;
}
else
{
return false;
}
}
window.alert(validateEmail("a#b.c"));
window.alert(validateEmail("a #b.c"));
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<script>
function validateEmail(email) {
var re = new RegExp("^[^\\s#]+#[^\\s#]+?\\.[^\\s#]+$", "m");
console.log(email.match(re));
if(email.match(re))
{
return true;
}
else
{
return false;
}
}
console.log(validateEmail("a#b.c"));
</script>
</body>
</html>
Hope that helps. If you have any questions on specifics just let me know...
I have an input type =text in html and i have this js code in js file to show error message
var $form = $("#myid"),
$errorMsg = $("<span id='myerrormessagespan' class='error' style='color:red;'>*</span>");
var toReturn = 0;
$("input", $form).each(function () {
if ($(this).val() == "") {
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = 1;
}
else {
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
I am trying to convert this code to make range validator on input type=text field .dispalying only 5 digits in the textbox, but i couldn't achieve . Is there any easy way to do this ?
Thanks
Consider using the jQuery validation plugin instead, especially the rangelength method for your case. However, if you want to stick to the original code without using any library then I suggest you try the code below for example:
HTML:
<form id="myid" name="myid" method="post" action="/">name :
<input type="text" name="name" id="name" />age :
<input type="text" name="age" id="age" />
<input type="submit" id="submit" name="submit" value="Save" />
</form>
jQuery:
var $form = $("#myid"),
$errorMsg = $("<span id='myerrormessagespan' class='error' style='color:red;'>*</span>");
$("#submit").on("click", function () {
var toReturn = true;
$("input", $form).each(function () {
var value = $(this).val();
if((!$.trim(this.value).length) || (value.length > 5)) {
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = false;
}
else {
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
return toReturn;
});
Working JSFiddle Demo
I want that Name field should contain text only.
<html>
<head></head>
<body>
<form name="form1">
Name <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Can anyone tell me how can I do so using either HTML or Javascript.
Use this regex in your Javascript: /^[a-z]+$/i
WORKING DEMO
Javascript:
var submit = document.getElementById("submit");
submit.addEventListener("click", checkInput, false);
function checkInput(e){
e.preventDefault();
var pattern = /^[a-z]+$/i;
alert(pattern.test(document.getElementById('text').value));
}
You can test whether there's "anything left" after removing alpha characters.
<html>
<body>
<form name="form1" onsubmit="return checkform();">
Name<input type="text" name="fname" id="fname">
<input type="submit" value="Submit">
</form>
<script>
function checkform(){
var fname=document.getElementById('fname').value;
if (fname.replace(/\w/g,'')!=''||fname==''){
alert('invalid firstname!');
return false;
}
return true;
}
</script>
</body>
</html>
try this:
<script type="text/javascript">
function validate(){
var allowedChars="abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var n=form1.fname.value;
for(var i=0;i<n.length;i++){
if(allowedChars.indexOf(n.charAt(i))==-1){
return false; // contains other char
}
}
return true; //valid name
}
Try regular expressions like
var match_text = /[a-zA-Z]/;
try this var regx = /^[A-Za-z][-a-zA-Z ]+$/;
function validate_form();
{
var regx = /^[A-Za-z][-a-zA-Z ]+$/;
var fname = document.getElementById('fname').value;
if(fname=="")
{
alert("Name is Blank");
return false;
}
else if(!regx.test(fname))
{
alert("name must contains character only");
return false;
}
else
{
return true;
}
}
Pattern checking of the textbox must be done with Javascript or Jquery like in other answers BUT if you want to use HTML5, you can directly write :
<input type="text" name="fname" id="fname" pattern="[A-Za-z]+" />
(See 'pattern' attribute in HTML5 if you're interested).
You can call this function to validate input field containing only text--
function validate()
{
str = document.form1.fname.value;
var patt = new RegExp("^[a-zA-Z ]*$");
var res = patt.test(str);
if(!res)
{
alert("do not match!");
return false;
}
}
<script type='text/javascript'>
function required()
{
var empt = document.forms["form1"]["Name"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
}
</script>
<form name="form1" method="" action="">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="address line1" value="Address Line 1"/><br />
I have more than one input text field, each having their default value. Before I submit the form I have to verify whether all fields are filled. So far i got the javascript to check for null since different text boxes have different default value. How can I write a javascript to verify that user has entered data? I mean, the script must identify that input data is other than default and null.
If you are not using jQuery then I would simply write a validation method that you can be fired when the form is submitted. The method can validate the text fields to make sure that they are not empty or the default value. The method will return a bool value and if it is false you can fire off your alert and assign classes to highlight the fields that did not pass validation.
HTML:
<form name="form1" method="" action="" onsubmit="return validateForm(this)">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="addressLine01" value="Address Line 1"/><br />
<input type="submit"/>
</form>
JavaScript:
function validateForm(form) {
var nameField = form.name;
var addressLine01 = form.addressLine01;
if (isNotEmpty(nameField)) {
if(isNotEmpty(addressLine01)) {
return true;
{
{
return false;
}
function isNotEmpty(field) {
var fieldData = field.value;
if (fieldData.length == 0 || fieldData == "" || fieldData == fieldData) {
field.className = "FieldError"; //Classs to highlight error
alert("Please correct the errors in order to continue.");
return false;
} else {
field.className = "FieldOk"; //Resets field back to default
return true; //Submits form
}
}
The validateForm method assigns the elements you want to validate and then in this case calls the isNotEmpty method to validate if the field is empty or has not been changed from the default value. it continuously calls the inNotEmpty method until it returns a value of true or if the conditional fails for that field it will return false.
Give this a shot and let me know if it helps or if you have any questions. of course you can write additional custom methods to validate numbers only, email address, valid URL, etc.
If you use jQuery at all I would look into trying out the jQuery Validation plug-in. I have been using it for my last few projects and it is pretty nice. Check it out if you get a chance. http://docs.jquery.com/Plugins/Validation
<form name="myForm" id="myForm" method="post" onsubmit="return validateForm();">
First Name: <input type="text" id="name" /> <br />
<span id="nameErrMsg" class="error"></span> <br />
<!-- ... all your other stuff ... -->
</form>
<p>
1.word should be atleast 5 letter<br>
2.No space should be encountered<br>
3.No numbers and special characters allowed<br>
4.letters can be repeated upto 3(eg: aa is allowed aaa is not allowed)
</p>
<button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>
validateForm = function () {
return checkName();
}
function checkName() {
var x = document.myForm;
var input = x.name.value;
var errMsgHolder = document.getElementById('nameErrMsg');
if (input.length < 5) {
errMsgHolder.innerHTML =
'Please enter a name with at least 5 letters';
return false;
} else if (!(/^\S{3,}$/.test(input))) {
errMsgHolder.innerHTML =
'Name cannot contain whitespace';
return false;
}else if(!(/^[a-zA-Z]+$/.test(input)))
{
errMsgHolder.innerHTML=
'Only alphabets allowed'
}
else if(!(/^(?:(\w)(?!\1\1))+$/.test(input)))
{
errMsgHolder.innerHTML=
'per 3 alphabets allowed'
}
else {
errMsgHolder.innerHTML = '';
return undefined;
}
}
.error {
color: #E00000;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Validation</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var tags = document.getElementsByTagName("input");
var radiotags = document.getElementsByName("gender");
var compareValidator = ['compare'];
var formtag = document.getElementsByTagName("form");
function validation(){
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
//Validation for Textbox Start
if(tags[i].type == "text"){
if(tagval == "" || tagval == null){
var lbl = $(tags[i]).prev().text();
lbl = lbl.replace(/ : /g,'')
//alert("Please Enter "+lbl);
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Please Enter "+lbl+"</span>");
$("#"+tagid).focus();
//return false;
}
else if(tagval != "" || tagval != null){
$(".span"+tagid).remove();
}
//Validation for compare text in two text boxes Start
//put two tags with same class name and put class name in compareValidator.
for(var j=0;j<compareValidator.length;j++){
if((tagval != "") && (tagclass.indexOf(compareValidator[j]) != -1)){
if(($('.'+compareValidator[j]).first().val()) != ($('.'+compareValidator[j]).last().val())){
$("."+compareValidator[j]+":last").after("<span style='color:red;' class='span"+tagid+"'>Invalid Text</span>");
$("span").prev("span").remove();
$("."+compareValidator[j]+":last").focus();
//return false;
}
}
}
//Validation for compare text in two text boxes End
//Validation for Email Start
if((tagval != "") && (tagclass.indexOf('email') != -1)){
//enter class = email where you want to use email validator
var reg = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/
if (reg.test(tagval)){
$(".span"+tagid).remove();
return true;
}
else{
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Email is Invalid</span>");
$("#"+tagid).focus();
return false;
}
}
//Validation for Email End
}
//Validation for Textbox End
//Validation for Radio Start
else if(tags[i].type == "radio"){
//enter class = gender where you want to use gender validator
if((radiotags[0].checked == false) && (radiotags[1].checked == false)){
$(".span"+tagid).remove();
//$("#"+tagid").after("<span style='color:red;' class='span"+tagid+"'>Please Select Your Gender </span>");
$(".gender:last").next().after("<span style='color:red;' class='span"+tagid+"'> Please Select Your Gender</span>");
$("#"+tagid).focus();
i += 1;
}
else{
$(".span"+tagid).remove();
}
}
//Validation for Radio End
else{
}
}
//return false;
}
function Validate(){
if(!validation()){
return false;
}
return true;
}
function onloadevents(){
tags[tags.length -1].onclick = function(){
//return Validate();
}
for(var j=0;j<formtag.length;j++){
formtag[j].onsubmit = function(){
return Validate();
}
}
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
if((tags[i].type == "text") && (tagclass.indexOf('numeric') != -1)){
//enter class = numeric where you want to use numeric validator
document.getElementById(tagid).onkeypress = function(){
numeric(event);
}
}
}
}
function numeric(event){
var KeyBoardCode = (event.which) ? event.which : event.keyCode;
if (KeyBoardCode > 31 && (KeyBoardCode < 48 || KeyBoardCode > 57)){
event.preventDefault();
$(".spannum").remove();
//$(".numeric").after("<span class='spannum'>Numeric Keys Please</span>");
//$(".numeric").focus();
return false;
}
$(".spannum").remove();
return true;
}
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", onloadevents, false);
}
//window.onload = onloadevents;
</script>
</head>
<body>
<form method="post">
<label for="fname">Test 1 : </label><input type="text" title="Test 1" id="fname" class="form1"><br>
<label for="fname1">Test 2 : </label><input type="text" title="Test 2" id="fname1" class="form1 compare"><br>
<label for="fname2">Test 3 : </label><input type="text" title="Test 3" id="fname2" class="form1 compare"><br>
<label for="gender">Gender : </label>
<input type="radio" title="Male" id="fname3" class="gender" name="gender" value="Male"><label for="gender">Male</label>
<input type="radio" title="Female" id="fname4" class="gender" name="gender" value="Female"><label for="gender">Female</label><br>
<label for="fname5">Mobile : </label><input type="text" title="Mobile" id="fname5" class="numeric"><br>
<label for="fname6">Email : </label><input type="text" title="Email" id="fname6" class="email"><br>
<input type="submit" id="sub" value="Submit">
</form>
</body>
</html>
function hasValue( val ) { // Return true if text input is valid/ not-empty
return val.replace(/\s+/, '').length; // boolean
}
For multiple elements you can pass inside your input elements loop their value into that function argument.
If a user inserted one or more spaces, thanks to the regex s+ the function will return false.
<pre><form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form></pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Plese Enter Name");
</script>
before using above code you have to add the gen_validatorv31.js js file
For flexibility and other places you might want to validated. You can use the following function.
`function validateOnlyTextField(element) {
var str = element.value;
if(!(/^[a-zA-Z, ]+$/.test(str))){
// console.log('String contain number characters');
str = str.substr(0, str.length -1);
element.value = str;
}
}`
Then on your html section use the following event.
<input type="text" id="names" onkeyup="validateOnlyTextField(this)" />
You can always reuse the function.