简体   繁体   中英

How to validate more than one form in same page without changing JS validation format

I currently have a JSP page that contains two forms:

<body>
   <form id="1"></form>
   <form id="2"></form>
</body>

Only one form will be showing at the time when viewing the page.

There is a JS validation file that is being used to check the form integrity when submit. To simply put, this JS file cannot be changed. Whenever the JS file is being called, the core function takes in the form.

function validateForm(formToValidate){}

The validation result alert is a JSP page id="alertMessage" , being hidden at the beginning by CSS:

#alertMessage {
  display: none;
} 

When any validation error happens, the page turns to visible by simple jQuery: $("#alertMessage").show();

The CSS requires the id="alertMessage" to not display the alert JSP page, and the JS requires the id="alertMessage" to do validation, and show alert messages.

Since I am having two forms in the page and the forms contain different content for validation, I have to include two JSP alerts in my page.

<body>
   <jsp:include page="alert for form 1">
   <form id="1"></form>

   <jsp:include page="alert for form 2">
   <form id="2"></form>
</body>

The issue: Not only I am having duplicate ids id="alertMessage" in one page, it is always the first JSP alert page being picked. So even I am submitting form 2, the alert for form 1 will be triggered. Combing the alerts into one JSP alert page is not an option due to my design limitation.

How do I fix this?

These slight modifications should help you.

Pass the form id in the function validateForm(formToValidate) as formToValidate parameter.

Remove the id tag from the error message containers. Add class="alertMessage" as attribute to the same.

Instead of $("#alertMessage").show(); use $("#"+formToValidate+" .alertMessage").show(); . Define the style for the class .alertMessage as below

.alertMessage {
  display: none;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM