2017-01-31 4 views
0

Привет, я выполняю проверку стороны на стороне поля, вижу, что я получаю все сообщения об ошибках правильно, но как избежать специальных символов, таких как% # $^& * для каждого поля ввода и способа ввода коробка граница становится красным, когда я получаю сообщения об ошибкахКак избежать специальных символов в Spring MVC

чтобы избежать специальных символов я должен использовать ESAPI.validator(). getValidInput Как использовать ниже Ьгу код улова в классе валидатора, чтобы избежать специальных символов

try 
    { 
ESAPI.validator().getValidInput("Validationofmobilenumber", mobilenumber, "Onlynumber", 200, false); 
      ESAPI.validator().getValidInput("Validationofinput", Studentname, "Onlycharacters", 200, false); 
    } 
    catch (ValidationException e) { 
       ESAPI.log().error(Logger.EVENT_FAILURE, e.getMessage()); 
       System.out.println("in validation"); 
       addActionError("Do not enter special character like % # $^& *...... "); 

      } catch (IntrusionException ie) { 
       ESAPI.log().error(Logger.EVENT_FAILURE, ie.getMessage()); 
    addActionError("Do not enter special character like % # $^& *...... "); 

      } catch (Exception e) { 
       System.out.println(e); 

      } 

Контроллер

@Controller 
public class RegistrationController { 

    @Autowired 
    CustomerValidator customerValidator; 



    @RequestMapping(value = "/register", method = RequestMethod.GET) 
     public String viewRegistrationPage(Model model) { 
      Customer customer = new Customer(); 
      model.addAttribute("customer", customer); 
      return "register"; 
     } 

    @RequestMapping(value = "/doRegister", method = RequestMethod.POST) 
     public String doLogin(@Valid Customer customer, BindingResult result,Model model) { 
     model.addAttribute("customer",customer); 
     customerValidator.validate(customer, result); 
      if(result.hasErrors()){ 
       return "register"; 
      } 

      return "home"; 
     } 

    public CustomerValidator getCustomerValidator() { 
     return customerValidator; 
    } 

    public void setCustomerValidator(CustomerValidator customerValidator) { 
     this.customerValidator = customerValidator; 
    } 

} 

Модель общественного класса Customer {

@NotEmpty 
    @Email 
    private String emailId; 

    @Size(min=8,max=15) 
    private String password; 


    @Size(min=8,max=15) 
    private String confPassword; 

    private int age; 

    public String getEmailId() { 
     return emailId; 
    } 

    public void setEmailId(String emailId) { 
     this.emailId = emailId; 
    } 

    public String getPassword() { 
     return password; 
    } 

    public void setPassword(String password) { 
     this.password = password; 
    } 

    public String getConfPassword() { 
     return confPassword; 
    } 

    public void setConfPassword(String confPassword) { 
     this.confPassword = confPassword; 
    } 

    public int getAge() { 
     return age; 
    } 

    public void setAge(int age) { 
     this.age = age; 
    } 

} 

Validator

@Component 
public class CustomerValidator implements Validator { 

    public boolean supports(Class<?> clazz) { 
     return Customer.class.isAssignableFrom(clazz); 
    } 

    public void validate(Object target, Errors errors) { 
     Customer customer = (Customer)target; 
     int age = customer.getAge(); 
     String password = customer.getPassword(); 
     String confPassword = customer.getConfPassword(); 


     ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age", "customer.age.empty"); 



     //Business validation 
     if(!password.equals(confPassword)){ 
      errors.rejectValue("password","customer.password.missMatch"); 
     } 


     if(age < 18 || age > 60){ 
      errors.rejectValue("age", "customer.age.range.invalid"); 
     }  
    } 
} 

Jsp

 <tr> 
      <td>Enter your E-mail:</td> 
      <td><form:input path="emailId" /></td> 
      <td><form:errors path="emailId" cssStyle="color: #ff0000;" /></td> 
     </tr> 

     <tr> 
      <td>Enter your Age:</td> 
      <td><form:input path="age"/></td> 
      <td><form:errors path="age" cssStyle="color: #ff0000;"/></td> 
     </tr> 

     <tr> 
      <td>Enter your password:</td> 
      <td><form:password path="password" showPassword="true"/></td> 
      <td><form:errors path="password" cssStyle="color: #ff0000;"/></td> 
     </tr> 

      <tr> 
      <td>Confirm your password:</td> 
      <td><form:password path="confPassword" showPassword="true"/></td> 
      <td><form:errors path="confPassword" cssStyle="color: #ff0000;"/></td> 
     </tr> 

     <tr> 
      <td><input type="submit" name="submit" value="Click here to Register"></td> 
     </tr> 
    </table> 
</form:form> 

Свойства

NotEmpty.customer.emailId=Email Id is required. 
Email.customer.emailId=valid email id is required. 
Size.customer.password=Password should be minimum of 8 and maximum of 15 characters. 
Size.customer.confPassword=Password should be minimum of 8 and maximum of 15 characters. 
customer.age.empty = Age is required 
customer.age.range.invalid = Age should be between 18 to 60 
customer.password.missMatch = password and confirm password do not match 

ответ

1

Для проверки используйте @Pattern аннотацию, как это:

@Pattern(regexp = "^[a-zA-Z0-9.\\-\\/[email protected]_ ]*$") 
    @NotEmpty 
    @Email 
    private String emailId; 

И для поля ошибки красной каймой, добавить класс CSS на наличие ошибок и поставить стиль CSS для этого класса и положить, что в головном блоке или в JSP файл css, который у вас есть.

<tr> 
     <td>Enter your E-mail:</td> 
     <td><form:input path="emailId" /></td> 
     <td><form:errors path="emailId" cssClass="error" /></td> 
    </tr> 

    <style> 
     .error { 
      color: red; 
      border: 1px solid red; 
     } 
    </style> 

Если вы хотите использовать ESAPI валидатор, добавьте это правило в своих ESAPI.properties

Validator.ValidInput=^[a-zA-Z0-9.\\-\\/[email protected]_ ]*$ 

, а затем добавить следующее для каждого из введенных в классе Validator, я даю только один для пример.

 try { 
      if (!ESAPI.validator().isValidInput("ValidationOfPassword", password, "ValidInput", 200, false)) { 
       errors.rejectValue("password","customer.password.missMatch");//replace your msg property in second param 
      } 
     } catch (Exception e) { 
      //something gone wrong 
      e.printStackTrace(); 
      errors.rejectValue("password","customer.password.missMatch");//replace your msg property in second param 
     } 
+0

я обновил мой ответ – mhshimul

+0

я сделал это .... где в любом файле свойств в проекте spring в eclipse –

+0

, если вы используете maven, добавьте свои файлы свойств в каталог ресурсов. – mhshimul

0

На вашем поле, вы можете использовать javax.validation.constraints.Pattern аннотацию, а затем использовать что-то вроде "[\ ш] *", что означает только буквенно-цифровые символы.

+0

Я думаю, вам нужно будет добавить несколько якорей к тому, как^[\ ш] * $ так, что он пытается сопоставить шаблон со всей области, а не только его часть –

Смежные вопросы