在WSO2 MI 1.2.0中验证yyyy-MM-dd格式字符串日期的问题咨询及解决方案寻求
Hey, I get your frustration with the new Date() function letting invalid dates slip through—this is a common issue because JavaScript's Date object automatically "fixes" invalid dates instead of rejecting them. Let's fix this for your WSO2 MI 1.2.0 setup, with a few different approaches to choose from:
1. Fix Your Existing Script Mediator Code
We'll avoid relying solely on new Date() for validation by manually breaking down the date components and checking each rule explicitly. Here's the revised script:
<script language="js"><![CDATA[ var myDate = mc.getProperty("myDate"); var isMyDateValid = 'false'; if(isValidDate(myDate)) { isMyDateValid = 'true'; } function isValidDate(dateString) { var log = mc.getServiceLog(); log.info("Validating date: " + dateString); // Step 1: Strict regex to filter out non-numeric characters and wrong format var regEx = /^\d{4}-\d{2}-\d{2}$/; if(!dateString.match(regEx)) { log.info("Invalid format: Must be yyyy-MM-dd"); return false; } // Split into year, month, day (note: months are 0-based in JS Date) var parts = dateString.split('-'); var year = parseInt(parts[0], 10); var month = parseInt(parts[1], 10) - 1; var day = parseInt(parts[2], 10); // Step 2: Validate month range (1-12 translates to 0-11) if(month < 0 || month > 11) { log.info("Invalid month: " + (month + 1)); return false; } // Step 3: Validate day count for the given month/year (accounts for leap years) // new Date(year, month+1, 0) returns the last day of the target month var daysInMonth = new Date(year, month + 1, 0).getDate(); if(day < 1 || day > daysInMonth) { log.info("Invalid day: " + day + " for month " + (month + 1)); return false; } // Final check: Ensure the parsed date matches the original string (no silent corrections) var parsedDate = new Date(year, month, day); return parsedDate.toISOString().slice(0,10) === dateString; } mc.setProperty("isMyDateValid", isMyDateValid); ]]></script>
Why this works:
- We first use regex to block invalid formats like
2021-1r-09or2020-10-09t - We manually validate month range to catch
2021-14-03 - We calculate the exact number of days in the target month (including leap year checks) to reject dates like
2021-02-29or2021-03-32 - The final check ensures no silent date corrections slip through
2. Use WSO2's Built-in XPath Functions (Simplest Approach)
WSO2 MI supports XPath 2.0, which has strict date validation via xs:date. This is the most concise solution if you don't need custom logging:
<!-- First, check format with regex, then validate as xs:date --> <property name="isMyDateValid" expression="if (matches($ctx:myDate, '^\d{4}-\d{2}-\d{2}$') and fn:date($ctx:myDate) instance of xs:date) then 'true' else 'false'" scope="default" type="STRING"/>
Why this works:
- The
matches()function filters out invalid formats first fn:date($ctx:myDate)will throw an error if the date is invalid (like2021-02-29), which theinstance of xs:datecheck catches cleanly- No custom scripting needed—uses WSO2's native capabilities
3. Validate with XSD Schema (For XML Payloads)
If you're validating a date within an XML payload, use WSO2's Validate Mediator with an XSD that enforces the xs:date type:
Step 1: Define the XSD (store it in the Registry as dateValidationSchema)
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="DatePayload"> <xs:complexType> <xs:sequence> <xs:element name="myDate" type="xs:date"/> </xs:sequence> </xs:complexType> </xs:schema>
Step 2: Use the Validate Mediator in your sequence
<validate source="//myDate" schema-key="dateValidationSchema"> <on-success> <property name="isMyDateValid" value="true" scope="default" type="STRING"/> </on-success> <on-fail> <property name="isMyDateValid" value="false" scope="default" type="STRING"/> <!-- Optional: Add logging or error handling here --> </on-fail> </validate>
Why this works:
- The
xs:datetype in XSD strictly enforces all date rules (leap years, month/day ranges, valid format) - Perfect for scenarios where you need to validate entire XML structures, not just a single property
内容的提问来源于stack exchange,提问作者koko

