0

How to validate First Name and Last Name in one input textbox using javascript?i have one inputtext box.when i given first b=name then need to give one space and need to give lastname.when i given two spaces or more spaces after firstname need to validate lasname is required and remove all spaces and put one space between firstname and lastname.can anybody help me this.

Visualforce page:

<apex:inputtext value={!name} id="Name"/>
<apex:commandbutton onclick="validatenamevalue();"/>

javascript:

function validatenamevalue(){
   var name = document.getElementById('{!$Component.formId.Name}').value;
   if(name == '') {
     alert(firstname is required);
   } else if(!name.includes(' ')) {
     alert(last name is reqiured);
   }
}

when i given second space empty value is saving in lastname field.need to validate lastname is not empty.

  • 1
    If you have a wish to receive good answer then post your code – Santanu Boral Jan 18 '17 at 6:29
  • ok,i will updade my code. – user Jan 18 '17 at 6:31
  • 1
    First of all the apex:inputText needs to have value in double quotes i.e. <apex:inputtext value="{!name}" id="Name"/> – RCS Jan 18 '17 at 6:57
1

Try Below Code

VF Code

<apex:inputtext value="{!name}" id="Name"/>
<apex:commandbutton onclick="validatenamevalue();" reRender="someId"/>

Javascript

function validatenamevalue(){
   var name = document.getElementById('{!$Component.formId.Name}').value;
   if(name == '' || name == null) {
     alert('Please enter FirstName & LastName');
   } else if(name.indexOf(' ') > 0 && name.indexOf(' ') == name.length) {
     alert('Please Enter Last Name');
   }
}
0

You can refer the following link and modify your code accordingly - How to write Javascript validation for Visualforce page

0

You can use regex function for two consecutive spaces in visualForce page You can find the regex expression for javaScript in below link.

https://stackoverflow.com/questions/3758798/how-to-search-for-occurences-of-more-than-one-space-between-words-in-a-line

If you want to compare in visualForce page, use REGEX function of visualforce page. Below are the functions you can use in visualForce page(Search for regex function and program it accordingly).

https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_variables_functions.htm

Let me know if these were helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.